import json
from typing import Optional

from fastapi import FastAPI, Query
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该指定具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/get")
async def get_test(
        name: Optional[str] = Query(None, description="按姓名搜索"),
        age: Optional[int] = Query(None, description="按年龄搜索")
):

    print('这里是Get请求响应的数据')
    try:
        # 从users.json文件读取数据
        with open('users.json', 'r', encoding='utf-8') as f:
            users_data = json.load(f)

            filtered_users = users_data

            # 根据参数过滤数据
            if name is not None:
                filtered_users = [user for user in filtered_users if user["name"] == name]

            if age is not None:
                filtered_users = [user for user in filtered_users if user["age"] == age]

            # 构建响应消息
            conditions = []
            if name is not None:
                conditions.append(f"姓名={name}")
            if age is not None:
                conditions.append(f"年龄={age}")

            message = "获取所有用户成功" if not conditions else f"搜索条件: {', '.join(conditions)}"

            return {
                "message": message,
                "count": len(filtered_users),
                "users": filtered_users,
                "search_params": {
                    "name": name,
                    "age": age
                }
            }

    except FileNotFoundError:
        return {"error": "users.json文件不存在"}
    except json.JSONDecodeError:
        return {"error": "users.json文件格式错误"}


@app.post("/post")
async def post_test(user_data: dict):
    """接收用户数据并写入JSON文件（自动生成ID）"""
    print(f'接收到POST请求数据: {user_data}')

    try:
        # 读取现有数据
        try:
            with open('users.json', 'r', encoding='utf-8') as f:
                users_data = json.load(f)
        except FileNotFoundError:
            users_data = []

        # 自动生成ID（最大ID+1）
        if users_data:
            max_id = max([u.get('id', 0) for u in users_data])
            new_id = max_id + 1
        else:
            new_id = 1

        # 创建新用户对象
        new_user = {
            "id": new_id,
            "name": user_data.get('name', ''),
            "age": user_data.get('age', 0),
            "gender": user_data.get('gender', '')
        }

        # 验证必要字段
        if not new_user['name']:
            return {
                "success": False,
                "message": "姓名不能为空"
            }

        # 添加新用户
        users_data.append(new_user)

        # 写回文件
        with open('users.json', 'w', encoding='utf-8') as f:
            json.dump(users_data, f, ensure_ascii=False, indent=2)

        return {
            "success": True,
            "message": "用户添加成功",
            "user": new_user,
            "total_count": len(users_data)
        }

    except Exception as e:
        return {
            "success": False,
            "message": f"添加用户失败: {str(e)}",
            "error": str(e)
        }



